package com.learn.Future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 异步回调 类似与前端的ajax,并不是立即返回结果,会有一部分时间延迟
 *
 */
public class FutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //同步操作
        CompletableFuture future = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
                System.out.println("runAsync success!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        //future.get();

        //异步处理
        CompletableFuture<String> supplyFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //int reuslt = 10/0;
            return "supplyAsync success";
        }).whenComplete((u,t)->{
            //可以获取异步返回的数据,根据是否报错判断后续操作
            try {
                System.out.println("result=>"+u);
            } catch (Exception e) {
                System.out.println("exception=>"+t.getMessage());
            }
        });
        supplyFuture.get();

        System.out.println("main ok!");

    }


}
